package com.unionftech.common.permissions.tip.impl.adapter;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.unionftech.common.permissions.tip.IPermissionTipInfoAdapter;
import com.unionftech.common.permissions.tip.bean.PermissionInfoForJson;
import com.unionftech.common.permissions.tip.bean.PermissionTipInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;

public class RawPermissionTipInfoAdapter implements IPermissionTipInfoAdapter {
    private List<PermissionInfoForJson> list = null;

    /**
     * 从 res/raw 文件夹中读取 json 格式的权限场景说明信息
     *
     * @param context 上下文对象
     * @param rawId   资源id
     */
    public RawPermissionTipInfoAdapter(Context context, int rawId) {
        StringBuilder builder = new StringBuilder();
        Gson gson = new Gson();
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            //获取res/raw目录下的文件输入流
            inputStream = context.getResources().openRawResource(rawId);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
            //获取res/raw目录下配置的权限场景说明信息列表
            list = gson.fromJson(builder.toString(), new TypeToken<List<PermissionInfoForJson>>() {
            }.getType());
            if (list == null) {
                list = Collections.emptyList();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(inputStream, bufferedReader);
        }
    }

    private void close(InputStream inputStream, BufferedReader bufferedReader) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PermissionTipInfo getPermissionTipInfo(Context context, String permission) {
        PermissionTipInfo info = null;
        for (PermissionInfoForJson infoForJson : list) {
            info = infoForJson.changeToPermissionTipInfo(context, permission);
            if (info != null) {
                break;
            }
        }
        return info;
    }
}
